package com.neusoft.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.dto.DeptAddDto;
import com.neusoft.dto.DeptCondition;
import com.neusoft.mapper.DeptMapper;
import com.neusoft.mapper.EmpMapper;
import com.neusoft.model.Dept;
import com.neusoft.model.Emp;
import com.neusoft.service.DeptService;
import com.neusoft.utils.ResponseCode;
import com.neusoft.utils.ServerResponse;
import com.neusoft.vo.DeptBaseVo;
import com.neusoft.vo.DeptEmpFinVo;
import com.neusoft.vo.DeptListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    public IPage<DeptListVo> getDeptList(Integer pageNum, Integer pageSize) {
        pageNum = pageNum == null || pageNum <= 0L ? 1 : pageNum;
        pageSize = pageSize == null || pageSize <= 0L ? 2 : pageSize;
        IPage<Dept> page = new Page<>(pageNum, pageSize);
        IPage<Dept> deptPage = deptMapper.selectPage(page, new QueryWrapper<>());
        List<DeptListVo> deptListVos = getDeptListVos(deptPage.getRecords());
        IPage<DeptListVo> pageInfo = new Page<>();
        pageInfo.setTotal(deptPage.getTotal());
        pageInfo.setCurrent((int) deptPage.getCurrent());
        pageInfo.setSize((int) deptPage.getSize());
        pageInfo.setRecords(deptListVos);
        return pageInfo;
    }

    private List<DeptListVo> getDeptListVos(List<Dept> depts) {
        if (depts == null || depts.isEmpty()) {
            return Collections.emptyList();
        }

        // 获取部门领导的工号列表
        List<String> leaderNos = depts.stream()
                .map(Dept::getLeader)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 根据工号查询员工信息
        List<Emp> leaders = empMapper.selectList(new QueryWrapper<Emp>()
                .in("no", leaderNos));

        // 将员工信息按照工号进行分组
        Map<String, String> leaderNameMap = leaders.stream()
                .collect(Collectors.toMap(Emp::getNo, Emp::getEmpname));

        // 转换为 DeptListVo
        return depts.stream().map(dept -> {
            DeptListVo deptListVo = new DeptListVo();
            deptListVo.setId(dept.getId());
            deptListVo.setNo(dept.getNo());
            deptListVo.setDeptname(dept.getDeptname());
            deptListVo.setEmpAs(dept.getEmpAs());
            deptListVo.setStatus(dept.getStatus());
            deptListVo.setEmpname(leaderNameMap.getOrDefault(dept.getLeader(), ""));
            return deptListVo;
        }).collect(Collectors.toList());
    }
    @Override
    public IPage<DeptListVo> getDeptCondition(DeptCondition deptCondition, Integer pageNum, Integer pageSize) {
        if (deptCondition == null) {
            return getDeptList(pageNum, pageSize);
        }
        pageNum = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize <= 0 ? 2 : pageSize;
        IPage<Dept> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        if (deptCondition != null && deptCondition.getStatus() != null) {
            queryWrapper.eq("status", deptCondition.getStatus());
        }
        if (deptCondition != null && deptCondition.getName() != null && !deptCondition.getName().isEmpty()) {
            queryWrapper.eq("deptname", deptCondition.getName());
        }
        IPage<Dept> deptPage = deptMapper.selectPage(page, queryWrapper);
        List<DeptListVo> deptListVos = getDeptListVos(deptPage.getRecords());
        IPage<DeptListVo> pageInfo = new Page<>();
        pageInfo.setTotal(deptPage.getTotal());
        pageInfo.setCurrent((int) deptPage.getCurrent());
        pageInfo.setSize((int) deptPage.getSize());
        pageInfo.setRecords(deptListVos);
        return pageInfo;
    }
//    public PageInfo<DeptListVo> getDeptCondition(DeptCondition deptCondition,Integer pageNum, Integer pageSize) {
//        pageNum = pageNum == null || pageNum <= 0L ? 1 : pageNum;
//        pageSize = pageSize == null || pageSize <= 0L ? 2 : pageSize;
//        Page<Dept> page = new Page<>(pageNum, pageSize);
//        Page<Dept> deptPage = deptMapper.selectPage(page, new QueryWrapper<>().eq("status", deptCondition.getStatus()).eq("deptname", deptCondition.getName()));
//        List<DeptListVo> deptListVos = getDeptListVos(deptPage.getRecords());
//        PageInfo<DeptListVo> pageInfo = new PageInfo<>(deptListVos);
//        pageInfo.setTotal(deptPage.getTotal());
//        pageInfo.setPageNum((int) deptPage.getCurrent());
//        pageInfo.setPageSize((int) deptPage.getSize());
//        return pageInfo;
////        pageNum = pageNum == null || pageNum <= 0L ? 1 : pageNum;
////        pageSize = pageSize == null || pageSize <= 0L ? 2 : pageSize;
////
////        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
////        queryWrapper.eq("status", deptCondition.getStatus());
////        queryWrapper.eq("deptname", deptCondition.getName());
////        queryWrapper.last("limit " + (pageNum - 1) * pageSize + "," + pageSize);
////        List<Dept> depts = deptMapper.selectList(queryWrapper);
////        return new PageInfo<>(getDeptListVos(depts));
//    }

    @Override
    public DeptBaseVo getDeptById(Integer id) {
        Dept dept = deptMapper.selectOne(new QueryWrapper<Dept>().eq("id", id));
        DeptBaseVo deptBaseVo = new DeptBaseVo();
        deptBaseVo.setDeptname(dept.getDeptname());
        deptBaseVo.setEmpAs(dept.getEmpAs());
        deptBaseVo.setFoundDate(dept.getFoundDate());
        deptBaseVo.setLeader(Integer.valueOf(dept.getLeader()));
        deptBaseVo.setNo(dept.getNo());
        deptBaseVo.setStatus(dept.getStatus());
        deptBaseVo.setSuperiorDept(dept.getSuperiorDept());
        Emp leader = empMapper.selectOne(new QueryWrapper<Emp>().eq("id", dept.getLeader()));
        if (leader != null) {
            deptBaseVo.setEmpname(leader.getEmpname());
        } else {
            deptBaseVo.setEmpname("未知"); // 或其他默认值
        }
        return deptBaseVo;
    }
    @Override
    public List<DeptEmpFinVo> getDeptEmpById(Integer id) {
        return deptMapper.getDempEmpById(id);

    }
    @Override
    public ResponseCode updateDeptStatus(Integer id) {
        List<DeptEmpFinVo> deptEmpById = getDeptEmpById(id);
        if (deptEmpById != null && !deptEmpById.isEmpty()) {
            return ResponseCode.ERROR;
        } else {
            Dept dept = deptMapper.selectById(id);
            if (dept.getStatus() == 0) {
                dept.setStatus(1);
            } else {
                dept.setStatus(0);
            }
            deptMapper.updateById(dept);
            return ResponseCode.SUCCESS;
        }
//        return null;
    }
    @Override
    public ServerResponse addDept(DeptAddDto deptAddDto) {
        if (deptAddDto != null) {
            Dept dept = new Dept();
            Dept existDept = deptMapper.selectOne(new QueryWrapper<Dept>().eq("deptname", deptAddDto.getDeptname()));
            if (existDept != null) {
                return ServerResponse.success(400, "部门已存在", null);
            }else {
                dept.setFoundDate(DateUtil.parse(DateUtil.today()));
                dept.setDeptname(deptAddDto.getDeptname());
                dept.setLeader(deptAddDto.getLeader());
                dept.setEmpAs(deptAddDto.getEmpAs());
                dept.setSuperiorDept(deptAddDto.getSuperiorDept());
                dept.setNo(deptAddDto.getNo());
                dept.setStatus(1);
                dept.setEmpNum(0);
                //TODO:这里需要确定一下，审批人和考勤人员
                dept.setTimeKeeper(deptAddDto.getTimeKeeper());
                dept.setLeaveApprover(deptAddDto.getLeaveApprover());
                int insert = deptMapper.insert(dept);
                if (insert > 0) {
                    return ServerResponse.success(200, "添加成功", null);
                }else {
                    return ServerResponse.success(400, "添加失败", null);
                }
            }

        }else {
            return ServerResponse.success(400, "添加失败,啥也没传进来", null);
        }
    }

    @Override
    public ServerResponse<?> updateDept(Integer id, DeptAddDto deptAddDto) {
        Dept dept = deptMapper.selectById(id);
        Dept existDept = deptMapper.selectOne(new QueryWrapper<Dept>().eq("deptname", deptAddDto.getDeptname()));
        if (deptAddDto == null) {
            return ServerResponse.success(400, "修改失败,啥也没传进来", null);
        }else {
            dept.setDeptname(deptAddDto.getDeptname());
            dept.setLeader(deptAddDto.getLeader());
            dept.setEmpAs(deptAddDto.getEmpAs());
            dept.setSuperiorDept(deptAddDto.getSuperiorDept());
            dept.setNo(deptAddDto.getNo());
            dept.setTimeKeeper(deptAddDto.getTimeKeeper());
            dept.setLeaveApprover(deptAddDto.getLeaveApprover());
            int update = deptMapper.updateById(dept);
            if (update > 0) {
                return ServerResponse.success(200, "修改成功", update);
            }else {
                return ServerResponse.success(400, "修改失败", update);
            }
        }
    }
}
